﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Library.WebControls.SimpleCapcha {
	[SupportsEventValidation]
	[DesignTimeVisible(true)]
	[ToolboxData("<{0}:SpCapcha runat=server></{0}:SpCapcha>")]
	public class SpCapcha : BaseControl {
		private static readonly Type SpCapchaType = typeof(SpCapcha);
		private bool _init;
		private Image _imgage;

		internal const string Key = "lI@.Sy#PleCAp^h$_";
		public string CapchaKey {
			get {
				EnsureChildControls();
				return Info.CapchaKey;
			}
			set {
				EnsureChildControls();
				Info.CapchaKey = value;
			}
		}
		[

			DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
			NotifyParentProperty(true)
			]
		public FontInfo Font {
			get {
				var f = Info.Font;

				return f;
			}
		}

		public Unit Width {
			get {
				EnsureChildControls();
				return _imgage.Width;
			}
			set {
				EnsureChildControls();
				_imgage.Width = value;
				Info.Width = Convert.ToInt32(value.Value);
			}
		}
		public Unit Height {
			get {
				EnsureChildControls();
				return _imgage.Height;
			}
			set {
				EnsureChildControls();
				_imgage.Height = value;
				Info.Height = Convert.ToInt32(value.Value);
			}
		}
		public string CssClass {
			get {
				EnsureChildControls();
				return _imgage.CssClass;
			}
			set {
				EnsureChildControls();
				_imgage.CssClass = value;
			}
		}

		public string ToolTip {
			get {
				EnsureChildControls();
				return _imgage.ToolTip;
			}
			set {
				EnsureChildControls();
				_imgage.ToolTip = value;
			}
		}
		[
				Bindable(true),

				DefaultValue(""),
				Editor("System.Web.UI.Design.ImageUrlEditor", typeof(UITypeEditor)),
				UrlProperty()
				]
		public string CapchaRenderUrl {
			get {
				EnsureChildControls();
				return _imgage.ImageUrl;
			}
			set {
				EnsureChildControls();
				_imgage.ImageUrl = value;
			}
		}

		private CapchaInfo _designInfo;
		private CapchaInfo Info {
			get {
				if (DesignMode) {
					if (_designInfo == null) {
						_designInfo = new CapchaInfo();
						_designInfo.Font = new TextBox().Font;
					}
					return _designInfo;
				}
				var instanceKey = InstanceKey;
				if (instanceKey != null) {
					var info = Context.Session[instanceKey] as CapchaInfo;
					if (info == null) {
						if (_designInfo != null) {
							info = _designInfo;
						} else {
							info = new CapchaInfo();
							info.Font = new TextBox().Font;
						}
						Context.Session[instanceKey] = info;
					}

					return info;
				}
				if (_designInfo == null) {
					_designInfo = new CapchaInfo();
					_designInfo.Font = new TextBox().Font;
				}
				return _designInfo;


			}
		}

		private string InstanceKey {
			get {
				if (_init)
					return Key + ClientID;
				return null;
			}
		}

		public string Text {
			get { return Info.Text; }
			set { Info.Text = value; }
		}

		public override string ID {
			get {
				EnsureChildControls();
				return _imgage.ID;
			}
			set {
				EnsureChildControls();
				_imgage.ID = value;
			}
		}

		protected override void OnInit(EventArgs e) {
			base.OnInit(e);
			_init = true;
			if (!IsLibraryWebControlsCallback) {
				try {
					if (!Page.IsPostBack) {
						Context.Session[InstanceKey] = _designInfo;
					}
				} catch {

				}
			}

		}

		protected override void CreateChildControls() {
			_imgage = new Image();
			Controls.Add(_imgage);
		}
		public override string ClientID {
			get {
				EnsureChildControls();
				return _imgage.ClientID;
			}
		}
		public void ClearAllSimpleCapchaSession() {
			var keys = new List<String>();
			foreach (var obj in Context.Session.Keys) {
				var key = obj.ToString();
				if (key.StartsWith(Key, StringComparison.InvariantCulture)) {
					keys.Add(key);
				}
			}
			foreach (var key in keys) {
				Context.Session.Remove(key);
			}
		}
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			IncludeScriptOnLoad(SpCapchaType, "Js", "Library.WebControls.SimpleCapcha.include.SpCapcha.js", UtilLib, AjaxCoreLib);

		}
		protected override void CreateClientObjectAtRender(HtmlTextWriter writer) {

			//_imgage.ImageUrl = url;

			BeginScriptTag(writer);
			writer.Write(String.Format("var {0} = new SpCapcha();", ClientName));
			writer.Write(String.Format("{0}.Init('{0}','{1}','{2}',{3});",
				ClientName,
				ClientID,
			ResolveClientUrl(_imgage.ImageUrl),
				ClientEnable.ToString().ToLower()
				));
			EndScriptTag(writer);
		}

		public int TextPixelHeight {
			get {
				EnsureChildControls();
				return Info.TextHeight;
			}
			set {
				EnsureChildControls();
				Info.TextHeight = value;
			}
		}

		protected override void Render(HtmlTextWriter writer) {
			var url = _imgage.ImageUrl;
			if (url.IndexOf('?') > -1) {
				url += "&I=" + ClientID;
			} else {
				url += "?I=" + ClientID;
			}
			_imgage.ImageUrl = url;
			base.Render(writer);
		}


		internal class CapchaInfo {
			public FontInfo Font { get; set; }
			public int Width { get; set; }
			public int Height { get; set; }
			public string CapchaKey { get; set; }
			public string Text { get; set; }
			public int TextHeight { get; set; }
		}
	}
}
